<template>
  <div
      class="FormBox"
      @click.stop
      @dblclick.stop
  >
    <div
      class="FormBox-hd"
      :class="{
        FormH32:size==='small',
      }"
    >
      <template v-if="['单行文本','多行文本','密码'].includes(formType)">
        <el-input
          v-model.trim="form[prop]"
          :placeholder="placeholder || '请输入'"
          :size="size"
          :disabled="disabled"
          :clearable="['密码'].includes(formType)?false:clearable"
          :type="typeName(formType)"
          :rows="['多行文本'].includes(formType)?4:''"
          :show-password="['密码'].includes(formType)"
          @change="changeBtn"
        >
          <template #prefix v-if="icon">
            <i class="iconfont" :class="icon"></i>
          </template>
          <template #suffix v-if="unit">
            <span style="padding-right:4px">{{unit}}</span>
          </template>
        </el-input>
      </template>
      <template v-else-if="['下拉单选','下拉多选'].includes(formType)">
        <el-select
          v-model.trim="form[prop]"
          :disabled="disabled"
          :size="size"
          :clearable="clearable"
          :placeholder="placeholder || '请选择'"
          filterable
          :multiple="['下拉多选'].includes(formType)"
          :collapse-tags="['下拉多选'].includes(formType) && tags"
          @change="changeBtn"
        >
          <el-option
            v-for="(item,index) in options"
            :key="prop+index"
            :label="item[labelName]"
            :value="item[valueName]"
            :disabled="item.disabled"
          >

            <div class="listRight8" v-if="$scopedSlots.option">
              <slot name="option" :option="item"/>
            </div>
          </el-option>
          <template #prefix v-if="icon">
            <i class="iconfont" :class="icon"></i>
          </template>
        </el-select>
      </template>
      <template v-else-if="['日期选择','日期范围'].includes(formType)">
        <el-date-picker
            v-model.trim="form[prop]"
            :disabled="disabled"
            :size="size"
            type="date"
            :placeholder="placeholder || '日期选择'"
            :type="typeName(formType)"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            :picker-options="pickerOptions"
        />
      </template>
      <template v-else-if="['单选框'].includes(formType)">
        <div>
          <el-radio-group
            v-model.trim="form[prop]"
            :disabled="disabled"
            :size="size"
            @change="changeBtn"
          >
            <el-radio
              v-for="(item,index) in options"
              :key="prop+index"
              :label="item[valueName]"
              :disabled="item.disabled"
            >
              <div class="listRight8" v-if="$scopedSlots.option">
                <slot name="option" :option="item"/>
              </div>
              <template v-else>{{item[labelName]}}</template>
            </el-radio>
          </el-radio-group>
        </div>
      </template>
      <template v-else-if="['复选框'].includes(formType)">
        <div>
          <el-checkbox-group
            v-model.trim="form[prop]"
            :disabled="disabled"
            :size="size"
            @change="changeBtn"
            v-if="form[prop] && form[prop].length>=0"
          >
            <el-checkbox
              v-for="(item,index) in options"
              :key="prop+index"
              :label="item[valueName]"
              :disabled="item.disabled"
            >
              <div class="listRight8" v-if="$scopedSlots.option">
                <slot name="option" :option="item"/>
              </div>
              <template v-else>{{item[labelName]}}</template>
            </el-checkbox>
          </el-checkbox-group>
        </div>
      </template>
      <template v-else-if="['单选','多选'].includes(formType)">
        <div class="tabsFlex">
          <div class="flex_m4">
            <div
              class="tabsFlex-item"
              v-for="(item,index) in options"
              :key="index"
              :class="{on:formType==='单选'?item.value===form[prop]:form[prop].includes(item.value)}"
              @click="onItem(item)"
            >
              <p>{{item[labelName]}}</p>
            </div>
          </div>
        </div>
      </template>
      <template v-else-if="['开关'].includes(formType)">
        <div>
          <el-switch
            v-model.trim="form[prop]"
            active-color="#06c156"
            :disabled="disabled"
            :size="size"
            class="not"
            :active-value="switchActive"
            :inactive-value="switchInactive"
            @change="changeBtn"
          />
        </div>
      </template>
      <template v-else-if="['计步器'].includes(formType)">
        <el-input-number
            v-model.trim="form[prop]"
            :size="size"
            :disabled="disabled"
            :min="min"
            :max="max"
            :step="step"
            :precision="precision"
            step-strictly
            :controls-position="controlsPosition"
            @change="changeBtn"
            clearable
        />
      </template>
      <template v-else-if="['数字','金额'].includes(formType)">
        <el-input
            v-model="form[prop]"
            type="number"
            :size="size"
            :disabled="disabled"
            :placeholder="placeholder || '请输入'"
            @blur="getNumber(['金额'].includes(formType)?2:0)"
            @change="changeBtn"
            clearable
        />
      </template>
      <template v-else-if="['文本搜索'].includes(formType)">
        <el-autocomplete
            v-model="form[prop]"
            class="inline-input"
            :fetch-suggestions="querySearch"
            placeholder="请输入内容"
            @input="handleInput"
            @select="handleSelect"
            :clearable="!isNew"
        >
          <template slot-scope="{ item }">
            <div class="name">{{ item[labelName] }}</div>
          </template>
          <template #suffix>
            <div class="el-input__icon" v-if="isNew && isAdd">
              <el-tooltip class="item" effect="dark" content="保存新增" placement="top">
                <i
                    class="el-icon-circle-plus-outline"
                    @click="handleAdd"
                />
              </el-tooltip>
            </div>
          </template>
          <template #prefix v-if="isNew && isAdd">
            <div class="el-input__icon">
              <span class="iconNew">新</span>
            </div>
          </template>
        </el-autocomplete>
      </template>
      <template v-else-if="['级联选择器','级联选择器多选'].includes(formType)">
        <el-cascader
            v-model.trim="form[prop]"
            :size="size"
            :disabled="disabled"
            :options="options"
            :props="{
              multiple: ['级联选择器多选'].includes(formType)
            }"
            :show-all-levels="showAll"
            clearable
            filterable
        >
          <template slot-scope="{ node, data }">
            <div class="listRight8" v-if="$scopedSlots.option">
              <slot name="option" :option="data"/>
            </div>
            <template v-else>{{data[labelName]}}</template>
          </template>
        </el-cascader>
      </template>
      <template v-else-if="['级联面板'].includes(formType)">
        <el-cascader-panel
            v-model.trim="form[prop]"
            :disabled="disabled"
            :options="options"
        >
          <template slot-scope="{ node, data }">
            <div class="listRight8" v-if="$scopedSlots.option">
              <slot name="option" :option="data"/>
            </div>
            <template v-else>{{data[labelName]}}</template>
          </template>
        </el-cascader-panel>
      </template>
    </div>
  </div>
</template>
<script>
export default {
  name: "FormBox",
  props: {
    form:{
      type:Object,
    },
    prop:{
      type:String,
    },
    icon:{
      type:String,
    },
    size:{
      type:String,
    },
    unit:{
      type:String,
    },
    placeholder:{
      type:String,
    },
    switchActive:{
      //开关开启的值
      default: () => {
        return true;
      },
    },
    switchInactive:{
      //开关关闭的值
      default: () => {
        return false;
      },
    },
    isAdd:{
      //文本搜索
      default: () => {
        return true;
      },
    },
    valueName:{
      //options实际值
      type:String,
      default: () => {
        return 'value';
      },
    },
    labelName:{
      //options标题值
      type:String,
      default: () => {
        return 'label';
      },
    },
    options:{
      type:Array,
    },
    formType:{
      type:String,
      default: () => {
        return '单行文本';
      },
    },
    controlsPosition:{
      type:String,
      default: () => {
        return 'right';
      },
    },
    clearable:{
      type:Boolean,
      default: () => {
        return true;
      },
    },
    disabled:{
      type:Boolean,
      default: () => {
        return false;
      },
    },
    tags:{
      type:Boolean,
      default: () => {
        return false;
      },
    },
    pickerOptions:{
      type:Object,
    },
    showAll:{
      //级联是否只最后一项
      type:Boolean,
      default: () => {
        return true;
      },
    },
    precision:{
      type:Number,
    },
    min:{
      type:Number,
      default: () => {
        return 1;
      },
    },
    max:{
      type:Number,
    },
    step:{
      type:Number,
      default: () => {
        return 1;
      },
    },
  }, // 获取父组件数据
  components: {

  },
  created() {
     this.info()
  },
  data() {
    return {
      isNew:false,
    };
  },
  methods: {
    getNumber(e){
      // 先把非数字的都替换掉，除了数字和 .
      this.form[this.prop] = this.form[this.prop].replace(/[^\d.]/g, "")
      // 保证只有出现一个 . 而没有多个 .
      this.form[this.prop] = this.form[this.prop].replace(/\.{2,}/g, ".")
      // 必须保证第一个为数字而不是.
      this.form[this.prop] = this.form[this.prop].replace(/^\./g, "0.")
      // 转换为数字
      this.form[this.prop] = this.form[this.prop]*1
      if (e!==0){
        this.form[this.prop] = this.form[this.prop].toFixed(e)*1
      }
    },
    //初始化
    info(){
      if (!this.form[this.prop] || this.form[this.prop]===false || this.form[this.prop]===0){
        if (['复选框','下拉多选','日期范围','级联选择器','级联选择器多选','级联面板'].includes(this.formType)){
          this.$set(this.form,this.prop,[])
        }else if (['数字','金额'].includes(this.formType)){
          this.$set(this.form,this.prop,null)
        }else if (['计步器'].includes(this.formType)){
          this.$set(this.form,this.prop,this.step)
        }else if (['开关'].includes(this.formType)){
          this.$set(this.form,this.prop,this.switchInactive)
        }else{
          this.$set(this.form,this.prop,'')
        }
      }
    },
    //类型
    typeName(val){
      let typeName=''
      if (['多行文本'].includes(val)){
        typeName='textarea'
      }else if(['日期选择'].includes(val)){
        typeName='date'
      }else if(['日期范围'].includes(val)){
        typeName='daterange'
      }
      return typeName
    },
    //
    querySearch(queryString, cb){
      var restaurants = this.options;
      var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant[this.labelName].indexOf(queryString) !== -1);
      };
    },
    handleSelect(val){
      this.form[this.prop]=val[this.labelName]
      this.isNew=false
    },
    handleInput(val){
      this.isNew=false
      if (val){
        let newArr=this.options.filter(item=>{
          return val===item[this.labelName]
        })
        if (newArr.length===0){
          this.isNew=true
        }
      }
    },
    //保存
    handleAdd(val){
      this.$emit('handleAdd',val,this.form)
    },
    //单选点击
    onItem(row){
      if (['单选'].includes(this.formType)){
        this.form[this.prop]=row[this.valueName]
      }else{
        if (this.form[this.prop].includes(row[this.valueName])){
          // 数组包含当前数据，执行删除操作
          let index = this.form[this.prop].indexOf(row[this.valueName]);
          this.form[this.prop].splice(index, 1);
        }else{
          // 数组不包含当前数据，执行新增操作
          this.form[this.prop].push(row[this.valueName])
        }
      }
      this.changeBtn(row[this.valueName])
    },
    //
    changeBtn(val){
      if (['下拉单选'].includes(this.formType)){
        let ogj={}
        this.options.forEach(item=>{
          if (item[this.valueName]===val){
            ogj[this.valueName]=item[this.valueName]
            ogj[this.labelName]=item[this.labelName]
          }
        })
        this.$emit('changeBtn',ogj,this.form)
      }else if (['下拉多选'].includes(this.formType)){
        let arr=[]
        this.options.forEach(item=>{
          if (val.includes(item[this.valueName])){
            let ogj={}
            ogj[this.valueName]=item[this.valueName]
            ogj[this.labelName]=item[this.labelName]
            arr.push(ogj)
          }
        })
        this.$emit('changeBtn',arr,this.form)
      }else{
        this.$emit('changeBtn',val,this.form)
      }
    },
  },
  computed: {

  }
};
</script>
<style  lang="scss" scoped>
.FormBox{
  .FormH32{
    min-height: 32px;
  }
  .FormBox-hd{
    display: flex;
    overflow: hidden;
    >*{
      &:not(.not){
        flex: 1;
      }
    }
  }
  .el-input__icon{
    display: inline-flex;
    align-items: center;
    justify-content: center;
    .el-icon-circle-plus-outline{
      cursor: pointer;
      font-size: 16px;
      &:hover{
        color: #3f61f1;
      }
    }
    .iconNew{
      width:20px;
      height:20px;
      display: inline-flex;
      align-items: center;
      justify-content: center;
      background: #06c156;
      color: #fff;
      border-radius:3px;
      font-size: 12px;
    }
  }
  .tabsFlex{
    .tabsFlex-item{
      padding: 0 10px;
      border-radius: 4px;
      cursor: pointer;
      height:32px;
      display: flex;
      align-items: center;
      background: #f5f5f5;
      &:hover{
        color: #3f61f1;
      }
      &.on{
        color: #fff;
        background: #3f61f1;
      }
    }
  }
}
::v-deep input::-webkit-outer-spin-button,
::v-deep input::-webkit-inner-spin-button {
  -webkit-appearance: none !important;
}
::v-deep input[type='number'] {
  -moz-appearance: textfield !important;
}
</style>
